<?php exit;

$firstimg = param('firstimg', '');
$expired = param('expired', '0');
if ($expired != 0) {
    $expired = strtotime($expired);
}
$source = param('source', '');
$sourceurl = param('sourceurl', '');

if ($TitleImgEnable) {
    $firstimg_tmp = pickup_title_pic($tid, $firstimg, (isset($GLOBALS['attach_imgs']) ? $attach_imgs : null));
    if (!empty($firstimg_tmp)) {
        $firstimg = $firstimg_tmp;
        unset($firstimg_tmp);
    }
}

if (isset($GLOBALS['attach_imgs'])) unset($GLOBALS['attach_imgs']);//清除临时变量
$dbopt_ret = null;
$keywords = param('keywords', '');
$metadesc = param('metadesc', '');
$relatedlinks = param('relatedlinks', '');
$relatedfids = param('relatedfids', '');
$keywordLs = $newLabelogs = null;
if ($IsThreadExtension) {
    $editornote = param('editornote', '');
    $reviseerr = param('reviseerr', '');
    $aflags = param('aflags', '0');
    $inscols = array('tid' => $tid, 'keywords' => $keywords, 'metadesc' => $metadesc, 'relatedlinks' => $relatedlinks, 'relatedfids' => $relatedfids, 'expired' => $expired, 'source' => $source, 'sourceurl' => $sourceurl, 'editornote' => $editornote, 'reviseerr' => $reviseerr, 'aflags' => $aflags);
    if ($TitleImgEnable) {
        $inscols['firstimg'] = $firstimg;
    }
    if($IsAdjustViewTemplate){
        $inscols['viwetemplate'] = param('viwetemplate', '');
    }
    if (!empty($keywords)) {
        $Label_extended_fields = array('distclass' => $fid);
        $keywordLs = StrToLabel($keywords, 'thread', true);
        if (!empty($keywordLs)) {
            $keywordLabels = array('lid' => &$keywordLs);
            $keywords_i = implode(',', array_keys($keywordLs));
            if ($keywords_i != $keywords)
                $updcols['keywords'] = $keywords = $keywords_i;
            unset($keywords_i);
            $newLabelogs = AddLabelLog($keywordLabels, $tid, 'thread', $Label_extended_fields);
            unset($keywordLabels);
        }
        unset($keywordLs);
    }
} else {
    $inscols = array('tid' => $tid, 'expired' => $expired, 'source' => $source, 'sourceurl' => $sourceurl);
    if ($TitleImgEnable) {
        $inscols['firstimg'] = $firstimg;
    }
}
if (!empty($keywords)) $inscols['relatedupdtime'] = time();
$dbopt_ret = db_insert($theadext_table, $inscols);
if ($dbopt_ret == 0) {//返回的是新的ID,但不是表的主键
    if (!empty($newLabelogs)) {//清除之前添加的labelog:
        $subtable_ids = array();
        foreach ($newLabelogs as $did => &$insCond) {
            if (!empty($insCond['lid'])) {
                $curLid = 0;
                $subtable_NO = null;
                $plid = &$insCond['lid'];
                if (is_numeric($plid)) {
                    $curLid = $plid;
                } elseif (is_array($plid)) {
                    if (isset($plid['subtable'])) {
                        $subtable_NO = intval($plid['subtable']);
                    } else {
                        $curLid = $plid['id'];;
                    }
                }
                if ($subtable_NO === null) {
                    if (empty($LabelCfg)) $LabelCfg = &GetPluginCfgNode('Label');//引用更快
                    $subtable_NO = GetSubtableId($LabelCfg['SubLabellog'], $curLid, false);
                }
                if ($subtable_NO !== null) {
                    $subtable_NO = intval($subtable_NO);
                    if (!isset($subtable_ids[$subtable_NO])) $subtable_ids[$subtable_NO] = array();
                    $subtable_ids[$subtable_NO][] = $did;
                }
            }
        }
        if (!empty($subtable_ids)) {
            $delCond = array('subtable' => &$subtable_ids);
            $delret = DelLabelLog($delCond, $tid, 'thread');
        }
        $newLabelogs = null;
    }
} else {
    if (!empty($newLabelogs) && !empty($keywordLs)) {//成功增加标签关联:
        $relatedlinkrules = $ExcludeDistRows = null;
        $must_include_links = array();
        $must_includes = 0;
        if ($relatedfids != '-1') {//不自动关联,只允许手动指定
            if (!empty($relatedlinks)) {
                $relatedlinkrules =  &ParseRelatedLinkExclude($relatedlinks);
                $ExcludeDistRows = array(array('table' => 'thread', 'id' => $tid));//先排除自身
                $edrs = array();
                if (!empty($relatedlinkrules)) {
                    foreach ($relatedlinkrules as &$relatedlinkrule) {
                        if (isset($relatedlinkrule['mark']) && !empty($relatedlinkrule['mark'])) {
                            if ($relatedlinkrule['mark'] == '!' || $relatedlinkrule['mark'] == '-')
                                $edrs[] = &$relatedlinkrule;
                            elseif ($relatedlinkrule['mark'] == '+' || $relatedlinkrule['mark'] == '*') {
                                $must_includes++;
                                $must_include_links[] = &$relatedlinkrule;
                            }
                        }
                    }
                }
                if (!empty($edrs)) $ExcludeDistRows = array_merge($ExcludeDistRows, $edrs);
            }
            if ($must_includes < 10) {
                $search_lg_conditions = array('disabled' => 0, 'fid' => $relatedfids);
                $Labelogs = &ListLabelog($keywordLs, $search_lg_conditions);
                if (!empty($Labelogs)) {
                    //必须把手动添加的关联项目加入排除:
                    if ($must_includes > 0)
                        $ExcludeDistRows_1 = array_merge($ExcludeDistRows, $must_include_links);
                    else
                        $ExcludeDistRows_1 = &$ExcludeDistRows;
                    $relatedArticles = &SelectiveLabelogs($Labelogs, $keywordLs, null, $ExcludeDistRows_1, 15 - $must_includes);
                    if (!empty($relatedArticles)) {
                        //此步与上步的排除不同:
                        $related_url_fmt = &GenerateRelatedLinks($relatedArticles, 10 - $must_includes, $ExcludeDistRows);
                        if (!empty($related_url_fmt)) {
                            $relatedlinks .= PHP_EOL . implode(PHP_EOL, $related_url_fmt);
                        }
                    }
                }
            }
        }
        unset($relatedlinkrules, $ExcludeDistRows, $must_includes, $search_lg_conditions, $Labelogs);
    }
}
unset($inscols);

//执行定期任务:
$__ticker = $tid / 100;
if ($__ticker == 0) $__ticker = 1;
$__ticker_val = mt_rand();

if ($__ticker_val % $__ticker == 0) {
    $ThreadextExpiredDeleted = array();//已经删除的过期主题帖子
    if (!empty($dbopt_ret)) {//启动清除过期帖子早期1000条
        $ExpiredThreadList = db_find($theadext_table, array('expired' => array('>' => 0, '<=' => time())), array('tid' => 1), 1, 512, 'tid', array('tid', 'expired', 'aflags'));//expired<0可能是定时发布任务
        if (!empty($ExpiredThreadList)) {
            foreach ($ExpiredThreadList as $tedel_tid => &$threadext_del) {
                $ThreadextExpiredDeleted[$tedel_tid] = thread_delete($tedel_tid);
            }
            //记录日志:
            xn_log("成功删除过期文章,运行环境:[UID:{$uid},IP:{$ip}],共" . strval(count($ThreadextExpiredDeleted)) . '篇,TID:(' . implode(',', array_keys($ThreadextExpiredDeleted)) . ')', 'task');
        }
    }
}

$__ticker = $tid / 10;
if ($__ticker == 0) $__ticker = 1;
$plan_rand = $__ticker_val % $__ticker;
//定期更新文章关联:
if ($plan_rand == 0) {
    $OldTimeLimit = time() - 3600 * 24 * 30;//一个月之前
    $OldRelatedlinksThreadList = db_find($theadext_table, array('relatedfids' => array('<>' => '-1'), 'relatedupdtime' => array('<' => $OldTimeLimit)), array('tid' => 0), 1, 512, 'tid', array('tid', 'keywords', 'relatedfids', 'relatedlinks', 'relatedupdtime', 'aflags'));//expired<0可能是定时发布任务
    if (!empty($OldRelatedlinksThreadList)) {
        $RelatedlinksThreadListUpdated = BulkUpdateRelatedLinks($OldRelatedlinksThreadList, 'thread');
        if (!empty($RelatedlinksThreadListUpdated)) {
            //记录日志:
            xn_log("成功更新文章的关联链接,运行环境:[UID:{$uid},IP:{$ip}],共" . strval(count($RelatedlinksThreadListUpdated)) . '篇,TID:(' . implode(',', array_keys($RelatedlinksThreadListUpdated)) . ')', 'task');
        }
    }
    unset($OldTimeLimit);

}
unset($__ticker, $plan_rand, $__ticker_val);

